from google.appengine.api import users

from django.conf import settings
from django.http import HttpResponsePermanentRedirect

from app import models

class AddUserToRequestMiddleware(object):
	"""Add a user object and a user_is_admin flag to each request."""

	def process_request(self, request):
		request.user = users.get_current_user()
		request.user_is_admin = users.is_current_user_admin()

		# Update the cached value of the current user's Account
		account = None
		if request.user is not None:
			account = models.Account.get_account_for_user(request.user)
			models.Account.current_user_account = account

class RedirectToHTTPSMiddleware(object):
	"""Redirect HTTP requests to the equivalent HTTPS resource."""
	def process_request(self, request):
		if settings.DEBUG or request.method == 'POST':
			return
		if not request.is_secure():
			host = request.get_host().split(':')[0]
			return HttpResponsePermanentRedirect(
				'https://%s%s' % (host, request.get_full_path()))
